package Test1;

import java.util.List;
import java.util.Scanner;

/**
 * 主程序类，负责用户交互和程序流程控制
 */
public class Main {
    private ExpressionGenerator generator;
    private Validator validator;
    private Scanner scanner;

    public Main() {
        this.generator = new ExpressionGenerator();
        this.validator = new Validator();
        this.scanner = new Scanner(System.in);
    }

    public void start() {
        System.out.println("=== 四则运算题目生成器 ===");
        System.out.println("支持加减乘除混合运算，结果和中间结果均为0-100之间的正整数");

        while (true) {
            showMenu();
            int choice = getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    generateQuestions();
                    break;
                case 2:
                    readFileContent();
                    break;
                case 3:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void showMenu() {
        System.out.println("\n=== 主菜单 ===");
        System.out.println("1. 生成题目");
        System.out.println("2. 读取文件");
        System.out.println("3. 退出");
    }

    private void generateQuestions() {
        System.out.println("\n=== 题目生成 ===");
        System.out.println("请选择题目类型:");
        System.out.println("1. " + ExpressionGenerator.getTypeName(ExpressionGenerator.PURE_ADDITION_2));
        System.out.println("2. " + ExpressionGenerator.getTypeName(ExpressionGenerator.PURE_SUBTRACTION_2));
        System.out.println("3. " + ExpressionGenerator.getTypeName(ExpressionGenerator.PURE_MULTIPLICATION_2));
        System.out.println("4. " + ExpressionGenerator.getTypeName(ExpressionGenerator.PURE_DIVISION_2));
        System.out.println("5. " + ExpressionGenerator.getTypeName(ExpressionGenerator.MIXED_ADD_SUB_2));
        System.out.println("6. " + ExpressionGenerator.getTypeName(ExpressionGenerator.MIXED_MUL_DIV_2));
        System.out.println("7. " + ExpressionGenerator.getTypeName(ExpressionGenerator.MIXED_4_OPERATIONS_2));
        System.out.println("8. " + ExpressionGenerator.getTypeName(ExpressionGenerator.MIXED_4_OPERATIONS_3));

        int type = getIntInput("请选择类型 (1-8): ");
        if (!validator.isValidType(type)) {
            System.out.println("无效的类型选择！");
            return;
        }

        int count = getIntInput("请输入题目数量: ");
        if (!validator.isValidCount(count)) {
            System.out.println("无效的数量！请输入1-1000之间的数字。");
            return;
        }

        int columns = getIntInput("请输入每行列数 (1-10): ");
        if (!validator.isValidColumns(columns)) {
            System.out.println("无效的列数！请输入1-10之间的数字。");
            return;
        }

        System.out.println("\n正在生成题目...");
        List<Expression> expressions = generator.generateExpressions(type, count);

        if (expressions.size() < count) {
            System.out.println("警告：只生成了 " + expressions.size() + " 道有效题目。");
            if (expressions.isEmpty()) {
                System.out.println("无法生成有效题目，请尝试其他类型。");
                return;
            }
        }

        // 显示题目
        displayExpressions(expressions, false, columns);

        // 保存选项
        System.out.print("\n是否保存到文件？(y/n): ");
        if (scanner.next().equalsIgnoreCase("y")) {
            saveFileOptions(expressions, columns);
        }
    }

    private void saveFileOptions(List<Expression> expressions, int columns) {
        System.out.println("请选择保存格式:");
        System.out.println("1. TXT格式");
        System.out.println("2. CSV格式");
        System.out.println("3. 两种格式都保存");

        int formatChoice = getIntInput("请选择 (1-3): ");

        System.out.print("请输入文件名前缀: ");
        String prefix = scanner.next();

        switch (formatChoice) {
            case 1:
                saveTxtFiles(expressions, prefix, columns);
                break;
            case 2:
                saveCsvFiles(expressions, prefix, columns);
                break;
            case 3:
                saveTxtFiles(expressions, prefix, columns);
                saveCsvFiles(expressions, prefix, columns);
                break;
            default:
                System.out.println("无效选择！");
        }
    }

    private void saveTxtFiles(List<Expression> expressions, String prefix, int columns) {
        FileUtil.saveToTxtFile(expressions, prefix + "_questions.txt", false, columns);
        FileUtil.saveToTxtFile(expressions, prefix + "_answers.txt", true, columns);
    }

    private void saveCsvFiles(List<Expression> expressions, String prefix, int columns) {
        FileUtil.saveToCSVFile(expressions, prefix + "_questions.csv", false, columns);
        FileUtil.saveToCSVFile(expressions, prefix + "_answers.csv", true, columns);
    }

    private void readFileContent() {
        System.out.print("请输入文件名: ");
        String filename = scanner.next();
        FileUtil.readFile(filename);
    }

    private void displayExpressions(List<Expression> expressions, boolean withAnswers, int columns) {
        String title = withAnswers ? "题目和答案" : "生成的题目";
        System.out.println("\n=== " + title + " ===");

        for (int i = 0; i < expressions.size(); i++) {
            Expression expr = expressions.get(i);
            String output;
            if (withAnswers) {
                output = (i + 1) + ". " + expr.toStringWithAnswer();
            } else {
                output = (i + 1) + ". " + expr.toString();
            }

            System.out.print(output);

            // 控制列数显示
            if ((i + 1) % columns == 0) {
                System.out.println();
            } else {
                System.out.print("\t\t");
            }
        }

        if (expressions.size() % columns != 0) {
            System.out.println();
        }
    }

    private int getIntInput(String prompt) {
        while (true) {
            System.out.print(prompt);
            if (scanner.hasNextInt()) {
                return scanner.nextInt();
            } else {
                System.out.println("请输入有效的数字！");
                scanner.next(); // 清除无效输入
            }
        }
    }

    public static void main(String[] args) {
        Main app = new Main();
        app.start();
    }
}